/**
 * 文件URL填充
 * @param path
 * @param type
 * @param w
 * @param h
 * @param mode
 * @returns {string}
 */
export const fileUrl = (path) => {
  if (!path) {
    return ''
  }
  if (!(/^https:|http:/.test(path) || path.indexOf(':') > -1)) {
    path = process.env.VUE_APP_FILE_PREFIX + '/' + path
  }
  return path
}

/**
 * 对象参数提取
 * @param fields
 * @param params
 * @param clone
 * @returns {*}
 */
export const extract = (fields, params, clone = false) => {
  const data = clone ? JSON.parse(JSON.stringify(fields)) : fields
  if (params) {
    for (const k in data) {
      // noinspection JSUnfilteredForInLoop
      data[k] = params[k] !== undefined ? params[k] : data[k]
    }
  }
  return data
}

/**
 * 转换金额
 * @param value
 * @param fractionDigits
 * @returns {string}
 */
export const decimal = (value, fractionDigits = 2) => {
  return (Math.floor(value * 100) / 100).toFixed(fractionDigits)
}

/**
 * 获取URL参数
 * @param name
 * @returns {string|null}
 */
export const urlParam = (name) => {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)')
    // eslint-disable-next-line no-undef
    .exec(location.href) || ['', ''])[1].replace(/\+/g, '%20')) || null
}

/**
 * base64远程图片
 * @param url
 * @returns {Promise<unknown>}
 */
export const imageBase64 = (url) => {
  function getBase64Image(image, width, height) { // width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
    const canvas = document.createElement('canvas')
    canvas.width = width || image.width
    canvas.height = height || image.height

    const ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
    return canvas.toDataURL()
  }
  const image = new Image()
  image.crossOrigin = ''
  image.src = url
  return new Promise((resolve, reject) => {
    try {
      image.onload = function() {
        resolve(getBase64Image(image))// 将base64传给done上传处理
      }
    } catch (err) {
      reject(null)
    }
  })
}

/**
 * 获取级联列表
 * @param tree   整个树
 * @param value  目标值
 * @returns {Promise<unknown>}
 */
export const getParentChain = function(tree, value, valueKey, resultKey) {
  let result = []
  const key = resultKey || valueKey
  if (!value || !tree) {
    return result
  }
  function getResult(tree, value, chain = []) {
    for (const item of tree) {
      const curChain = [...chain, item[key]]
      if (item[valueKey] === value) {
        result = curChain
        break
      }
      if (item.children && item.children.length > 0) {
        getResult(item.children, value, curChain)
      }
      if (result.length > 0) {
        break
      }
    }
  }
  getResult(tree, value)
  return result
}

/**
 * 时间戳转换为想要的时间格式
 */
export const dateFormat = function(fmt = 'yyyy-MM-dd hh:mm:ss') {
  const replaceMap = {
    'M+': this.getMonth() + 1,
    'd+': this.getDate(),
    'h+': this.getHours(),
    'm+': this.getMinutes(),
    's+': this.getSeconds(),
    'q+': Math.floor((this.getMonth() + 3) / 3),
    'S': this.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const key in replaceMap) {
    const value = replaceMap[key]
    if (new RegExp('(' + key + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (RegExp.$1.length === 1) ? value : (('00' + value).substr(('' + value).length))
      )
    }
  }
  return fmt
}

export default { urlParam }
